package com.ts.animal.controller;

import com.alibaba.fastjson.JSON;
import com.ts.animal.constant.AnimalConstant;
import com.ts.animal.domain.ExportRecordDO;
import com.ts.animal.service.ExportRecordService;
import com.ts.common.constant.CommonConstant;
import com.ts.common.controller.BaseController;
import com.ts.common.enums.Enums;
import com.ts.common.redis.RedisUtil;
import com.ts.common.utils.PageInfos;
import com.ts.common.utils.PageUtils;
import com.ts.common.utils.Result;
import com.ts.common.utils.UtilByte;
import com.ts.system.util.SystemUtil;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 导出文件记录表
 *
 * @author bobby
 * @email bobby@126.com
 * @date 2022-12-03 18:49:57
 */

@Controller
@RequestMapping("/animal/exportRecord")
public class ExportRecordController extends BaseController {
	@Autowired
	private ExportRecordService exportRecordService;

	@GetMapping()
	@RequiresPermissions("animal:exportRecord:exportRecord")
	String ExportRecord() {
		return "animal/exportRecord/exportRecord";
	}

	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("animal:exportRecord:exportRecord")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		//查询列表数据
		PageUtils pageUtils = new PageInfos(params) {
			@Override
			public List inject(Map params) {
				return exportRecordService.list(params);
			}
		}.query();
		return pageUtils;
	}


	@GetMapping("/add")
	@RequiresPermissions("animal:exportRecord:add")
	String add() {
		return "animal/exportRecord/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("animal:exportRecord:edit")
	String edit(@PathVariable("id") Integer id, Model model) {
		ExportRecordDO exportRecord = exportRecordService.get(id);
		model.addAttribute("exportRecord", exportRecord);
		return "animal/exportRecord/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("animal:exportRecord:add")
	public Result save(ExportRecordDO exportRecord) {
		Result result = Result.ok();
		exportRecordService.save(result, exportRecord);
		return result;
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("animal:exportRecord:edit")
	public Result update(ExportRecordDO exportRecord) {
		Result result = Result.ok();
		exportRecordService.update(result, exportRecord);
		return result;
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("animal:exportRecord:remove")
	public Result remove(Integer id) {
		Result result = Result.ok();
		exportRecordService.remove(result, id);
		return result;
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("animal:exportRecord:batchRemove")
	public Result remove(@RequestParam("ids[]") Integer[] ids) {
		Result result = Result.ok();
		exportRecordService.batchRemove(result, ids);
		return result;
	}


	@RequestMapping("/export")
	@ResponseBody
	public Result export(@RequestParam Map<String, Object> params) {
        Integer interval = Integer.valueOf(SystemUtil.getSystemParams().get(AnimalConstant.key_name_export_interval).getParamValue());
        String repetition = RedisUtil.get(AnimalConstant.REDIS_BASE_EXPORT_FLAG + getUserId());

//		if (StringUtils.isNotEmpty(repetition)) {
////			return Result.error().setMsg("您的操作太频繁，请" + interval + "秒后再导出数据");
////		}
        RedisUtil.set(AnimalConstant.REDIS_BASE_EXPORT_FLAG + getUserId(), getUserId(), interval, TimeUnit.SECONDS);

        String paramString = JSON.toJSONString(params).trim();
        ExportRecordDO exportRecord = new ExportRecordDO();
        exportRecord.setExportActionTime(new Date());
        exportRecord.setDeptId(getUser().getDeptId().intValue());
        exportRecord.setCreateUser(getUserId().intValue());
        exportRecord.setExportParams(JSON.toJSONString(params).trim());
        exportRecord.setExportStatus(AnimalConstant.export_being);
        exportRecord.setFunctionCode(params.get(CommonConstant.EXPORT_CODE_FLAG).toString());
		exportRecord.setFunctionDescribe(Enums.Export.getEnum(params.get(CommonConstant.EXPORT_CODE_FLAG).toString()).getText());
		Result result = Result.ok();
		exportRecordService.save(result, exportRecord);

		params.put(CommonConstant.EXPORT_USER, getUserId());
		params.put(CommonConstant.EXPORT_DEPT, getUser().getDeptId());
		params.put(CommonConstant.EXPORT_ID_FLAG, exportRecord.getId());
		RedisUtil.lpush(AnimalConstant.REDIS_BASE_EXPORT_PARAM_DATA_KEY, JSON.toJSONString(params).trim());
		return result.setMsg("后台正在导出文件，请前往文件管理中心下载文件");
	}

	@RequestMapping("/download/{id}")
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) throws IOException {
		ExportRecordDO exportRecord = exportRecordService.get(id);
		String path = exportRecord.getExportPath();
		String[] split = path.split("/");
		String fn = split[split.length - 1];
		fn = new String(fn.getBytes("GB2312"), "ISO_8859_1");
		byte[] data = UtilByte.fileToBytes(path);
		response.reset();
		response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fn));
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IOUtils.write(data, response.getOutputStream());
	}
}
